# Copyright (C) 2007 "dbsolution sas"
# Copyright (C) 2008 "Domenico Chierico" (spaghetty@gmail.com) 
#
# This file is part of Weebotee.
#
# Weebotee is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Weebotee is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Weebotee.  If not, see <http://www.gnu.org/licenses/>.

#the main plug features
from django.conf import settings
from apps.core.models.section import Section
from apps.core.models.element import Element
import re

clean_apps_list = lambda x: not re.search("django|filebrowser|apps.core",x)
clean_app_name = lambda x: re.match("^.+\.(.+)$",x).group(1)

# this method try to gather a specific method, named "mname" from all apps
# installed into the framework
def scan_applications(mname):
    """Scan installed apps looking for methods named mname, and
    return a complete list of application names, ref to method"""
    apps = filter(clean_apps_list, settings.INSTALLED_APPS)
    results = {}
    for ap in apps:
        elem = __import__(ap+".libs.plug", globals(), locals(), ["*"])
        try:
            method = getattr(elem,mname)
            results[ap] = method()
        except:
            pass
    return results

def get_method_in_app(name, method):
    apps = filter(clean_apps_list, settings.INSTALLED_APPS)
    m = None
    for ap in apps:
        if re.search(name,ap):
            elem = __import__(ap+".libs.plug", globals(), locals(), ["*"])
            if hasattr(elem, method):
                m = getattr(elem,method)
    return m

def get_model_from_etype(etype):
    """Maps etype into real models"""
    app = get_section(etype)
    app = "apps."+app
    elem = __import__(app+".models", globals(),locals(),["*"])
    for e in dir(elem):
        r = None
        try:
            r = getattr(elem,e)
        except Exception, e:
            r=None
        for x in dir(r):
            try:
                if r.__name__[0:app.__len__()] == app:
                    try:
                        a = getattr(r,x)
                        if a.__module__ == r.__name__ and a.__name__ == get_entity(etype):
                            return a
                    except:
                        pass
            except:
                pass

def get_form_for_etype(etype):
    part =  __import__("apps."+get_section(etype)+
                       ".forms."+get_entity(etype).lower()+
                       "_form",locals(),globals(),
                       [get_entity(etype).capitalize()+"Form",])
    form =  getattr(part,get_entity(etype).capitalize()+"Form")
    if form:
        return form

### only for backend management ###
def load_plug_urls():
    """collect all url exported from a plugins"""
    from django.conf.urls.defaults import include
    apps = filter(clean_apps_list, settings.INSTALLED_APPS)
    result = []
    for ap in apps:
        name = re.search("\.([a-z0-9_]+)$",ap)
        name = name.group(1)
        result.append(("^plugin/"+name+"/", include(ap+".urls")))
    return result

### will be deprecated in a few ###
def load_plug_services_urls():
    """urls for services"""
    from django.conf.urls.defaults import include
    apps = filter(clean_apps_list, settings.INSTALLED_APPS)
    result = []
    for ap in apps:
        name = re.search("\.([a-z0-9_]+)$",ap)
        name = name.group(1)
        result.append(("^services/"+name+"/", include(ap+".services")))
    return result 


## etype management ###
def get_entity(elem):
    if isinstance(elem,Element):
        value = elem.etype
    elif isinstance(elem,str) or isinstance(elem, unicode):
        value = elem
    else:
        value = ""
    index = value.find(":")
    value = value[index+1:value.__len__()]
    return value

def get_section(elem):
    """ into form 'app:entity' catch app statement"""
    if isinstance(elem,Element):
        value = elem.etype
    elif isinstance(elem,str) or isinstance(elem, unicode):
        value = elem
    else:
        value = ""
    index = value.find(":")
    return value[0:index]


### element renderizing stuff ###
def get_tmpl_from_plug(type, elem):
    return get_tmpl_from_etype(elem.etype, type)

def get_tmpl_from_etype(etype, type):
    app = get_section(etype)
    elem = get_entity(etype).lower()
    return "elements/"+elem+"/"+type+".html"

def get_all_rend_style(etype):
    import os
    paths = settings.TEMPLATE_DIRS
    elem = get_entity(etype)
    for path in paths:
        if path.find("resources") != -1:
            final = [os.path.splitext(x)[0] for x in os.listdir(
                    path+"/elements/"+elem.lower()) if x.endswith(".html")]
            return final
             
def get_view_for_elem(element):
    etype = element.etype
    if etype == "core:Article":
        return "fe_internal_detail.html"
    elif etype:
        app = get_section(etype)
        m = get_method_in_app(app,get_entity_part(etype).lower()+"_detail")
        return m()

def get_input_for_elem(element):
    app = get_section(element)
    m = get_method_in_app(app, get_entity_part(element).lower()+"_add")
    if m:
        return m()

### managing sections ###

def build_sections_list(values): #some trouble with uninstalled apps
    """Build the list of installed sections"""
    import os
    paths = settings.TEMPLATE_DIRS
    list=[]
    for path in paths:
        if path.find("resources") != -1:
            walker = os.walk(path+"/sections/")
            for dir in walker:
                if not dir[0].endswith("sections/") and dir[0].find(".svn")== -1:
                    pkg = os.path.split(dir[0])[1]
                    for sect in dir[2]:
                        if sect.endswith(".html"):
                            elem = sect.split('.')[0].capitalize()
                            desc = "%s view in %s"%(elem,pkg)
                            list.append((u""+pkg+":"+ elem, desc))
    return list

def get_view(section):
    """Find right template for a specific section"""
    view = section.viewtype
    app = get_section(view)
    return "sections/"+app+"/"+ get_entity(view).lower()+".html"
